import os
import sys

import webapp2
import jinja2

jinja_env=jinja2.Environment(
    loader=jinja2.FileSystemLoader(
        os.path.join(os.path.dirname(__file__), "templates")
        ))

sys.path.insert( 0, os.path.join(os.path.dirname(__file__),
    "wtforms-1.0.2.zip") )
import wtforms
from wtforms import Form, TextField
from wtforms.ext.appengine.db import model_form
from wtforms.fields import Label

from google.appengine.api import users
from google.appengine.ext import db

keyname = "v1"


class Spam(db.Model):
    text = db.TextProperty()
    created = db.DateTimeProperty(auto_now_add=True)


SpamForm=model_form(Spam, Form)


class Download(webapp2.RequestHandler):
    def get(self):
        spam = Spam.get_or_insert(keyname, text="")
        if spam is None:
            text = ""
        else:
            text = spam.text
        template = jinja_env.get_template('dl.html')
        self.response.write(template.render({
            'spam_text': text}))


class Upload(webapp2.RequestHandler):
    def post(self):
        template = jinja_env.get_template('upload.html')
        spam = Spam.get_or_insert(keyname, text="")
        form=SpamForm(formdata=self.request.POST, obj=spam)
        msg=""
        if form.validate():
            form.populate_obj(spam)
            spam.put()
            msg="successed!"
        else:
            msg="failure."

        self.response.write(template.render({
            'form': form,
            'spam': spam,
            'msg': msg }))
        return

    def get(self):
        template = jinja_env.get_template('upload.html')
        spam = Spam.get_or_insert(keyname, text="")

        form=SpamForm(obj=spam)

        self.response.write(template.render({
            'form': form,
            'spam': spam }))
        return


class Index(webapp2.RequestHandler):
    def get(self):
        template = jinja_env.get_template('index.html')
        self.response.write(template.render({}))
